#pragma once

#include "IWebsocketServer.h"
#include <mutex>
#include <map>
#include <list>
#include <sstream>
#include "WIceAgent.h"
#include "CommonSignalData.h"

struct PeerInfo
{
    string roomId = "";
    string userId = "";
    string userName = "";
    int64_t fd = -1;
    shared_ptr<WIceAgent> iceAgent = nullptr;
};

class WebsocketHandler: public IIceRecvCb
{
public:
    WebsocketHandler();
    virtual ~WebsocketHandler();
    void onWsReceiveMsg(shared_ptr<WsRequestMsg> &wsMsg);
    void onWsConnect(shared_ptr<WsRequestMsg> &wsMsg);
    void onWsCloseMsg(shared_ptr<WsRequestMsg> &wsMsg);
    bool start();

    // IIceRecvCb
    virtual void handleRecvRtp(shared_ptr<WsRequestMsg> wsRequest, char *data, int len);

private:
    IWebsocketServer *_websocketServer = nullptr;
    map<int64_t, PeerInfo> _fdToPeerInfo;
    map<string, list<PeerInfo>> _roomToPeerListMap;
    mutex _orderMutex;

    void handleJoinOrder(shared_ptr<WsRequestMsg> &wsMsg, SignalOrderInfo &orderInfo);
    void handleAnswerOfferOrder(shared_ptr<WsRequestMsg> &wsMsg, SignalOrderInfo &orderInfo);
    void handleIceCandiateOrder(shared_ptr<WsRequestMsg> &wsMsg, SignalOrderInfo &orderInfo);
    SignalOrderInfo parseOrderInfo(shared_ptr<WsRequestMsg> wsMsg);
    PeerInfo getPeerInfo(int64_t fd);
    list<PeerInfo> getPeerInfoList(int64_t fd);
    void transOrderInfoToPeerInfo(SignalOrderInfo &orderInfo, PeerInfo &peerInfo);
};

